package core.controller
{
	import com.greensock.TweenLite;
	
	import core.Config;
	import core.Util;
	import core.containers.ChipEffectContainer;
	
	import flash.geom.Point;
	import flash.utils.setTimeout;

	public class AddChipToPlayerController
	{
		private var chipEffectContainer:ChipEffectContainer;
		
		private var nextEffectContainer:ChipEffectContainer;
		
		private var p1:Point = Config.REMOVE_CHIP_POSITION;// 第一个动画到达的位置
		
		private var p2:Point;// 到达的位置
		
		private var lastEffectContainer:ChipEffectContainer;
		
		private var nextCallback:Function;
		
		public function AddChipToPlayerController(chipEffectContainer:ChipEffectContainer,nextEffectContainer:ChipEffectContainer,lastEffectContainer:ChipEffectContainer,p2:Point,nextCallback:Function)
		{
			this.chipEffectContainer = chipEffectContainer;
			this.nextEffectContainer = nextEffectContainer;
			this.lastEffectContainer = lastEffectContainer;
			this.p2 = p2;
			this.nextCallback = nextCallback;
		}
		
		public function execute():void {
			if(this.chipEffectContainer == null){
				this.toTableFunc();
				return;
			}
			var center:Point = Util.getCenter(p1,p2,0);
			TweenLite.to(chipEffectContainer, 0.5, {bezierThrough:[{x:center.x, y:center.y},{x:p2.x,y:p2.y}],onComplete:nextEffect});
		}
		
		private function nextEffect():void {// 第二个动画
			setTimeout(nextEffectFunc,300);
		}
		
		private function nextEffectFunc():void {
			var p3:Point = new Point(this.nextEffectContainer.x,this.nextEffectContainer.y);
			var center:Point = Util.getCenter(p2,p3,5);
			TweenLite.to(chipEffectContainer, 0.3, {bezierThrough:[{x:center.x, y:center.y},{x:p3.x,y:p3.y}],onComplete:toTable});
		}
		
		private function toTable():void {// 最后一个动画
			this.nextCallback();
			this.nextCallback = null;
			setTimeout(toTableFunc,300);
		}
		
		private function toTableFunc():void {
			var total:Number = 0;
			if(chipEffectContainer){
				total += chipEffectContainer.total
			}
			total += this.nextEffectContainer.total;
			this.nextEffectContainer.add(Util.split(total));
			Util.removeChild(chipEffectContainer);
			var p3:Point = new Point(this.nextEffectContainer.x,this.nextEffectContainer.y);
			var p4:Point = new Point(this.lastEffectContainer.x,this.lastEffectContainer.y);
			var center:Point = Util.getCenter(p3,p4,0.3);
			TweenLite.to(this.nextEffectContainer, 0.3, {bezierThrough:[{x:center.x, y:center.y},{x:p4.x,y:p4.y}],onComplete:onComplete});
		}
		
		private function onComplete():void {
			var total:Number = this.nextEffectContainer.total + this.lastEffectContainer.total;
			this.lastEffectContainer.add(Util.split(total));
			Util.removeChild(nextEffectContainer);
		}
	}
}